<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\BatchAction\CancelPatentGrantBatch;
use App\Admin\Actions\Post\TransactionPost;
use App\Exceptions\MsgException;
use App\Extensions\Exporters\PatentApplyExporter;
use App\Extensions\Renderable\PatentAgencyDetailRenderAble;
use App\Http\Controllers\Controller;
use App\Models\Department;
use App\Patent;
use App\PatentApply;
use App\Repositories\PatentApplyRepository;
use App\Services\PatentApplyService;
use App\Services\PatentService;
use Encore\Admin\Form;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Grid\Tools\BatchActions;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\DB;

class PatentController extends Controller
{
    protected $title = '已授权专利';
    public $repository;
    public $service;

    public function __construct(PatentApplyRepository $repository, PatentApplyService $service)
    {
        $this->repository = $repository;
        $this->service = $service;
    }

    public function index(Content $content)
    {
        $grid = $this->grid();
        $grid->header(function () {
            $year = request()->get('publication_date') ?: date('Y');
            $data = PatentApply::query()
                ->select(DB::raw('count(*) as count,patent_type_id'))
                ->whereYear('publication_date', $year)
                ->whereIn('status', [1, 2])
                ->where('review_status', 1)
                ->groupBy(['patent_type_id'])->get()->map(function ($item) {
                    return [
                        'name'  => data_get(patent_type_select_option(), $item['patent_type_id']),
                        'value' => $item['count']
                    ];
                })->pluck('value', 'name')->toArray();
            $title = $year . '年(公告):';
            return view('admin.statistics.common-table-header', compact('title', 'data'));
        });
        return $content
            ->title($this->title)
            ->body($grid);
    }

    protected function grid()
    {
        $grid = $this->repository->adminGrid();
        $grid = $this->service->gridColumns($grid, 1, 1);
        $grid->actions(function (Actions $actions) {
            $actions->disableView();
            $actions->disableEdit();
            if (!$actions->row->transaction) {
                $actions->prepend(new  TransactionPost($actions));
            }
        });
        $grid->batchActions(function (BatchActions $actions) {
            $actions->add(new CancelPatentGrantBatch());
        });
        $grid->disableCreateButton();
        $grid->disableExport(false);
        $grid->exporter((new PatentApplyExporter())->setRoleType(1)->setFileName('已授权专利' . date('Ymd')));
        return $grid;

    }

    //已受理 暂停
    public function index2(Content $content)
    {
        $grid = $this->repository->adminGrid();
        $grid->model()->collection(function ($collection) {
            return $collection->map(function ($item, $key) {
                $item->legal_status = $key % 2;
                return $item;
            });
        });
        $grid->model()->with(['remarks.user', 'assesses.expert', 'experts', 'department', 'agency', 'user']);
        $grid->model()->where('status', 1)->where('review_status', 1);
        $grid->column('uuid', __('登记编号'));
        $grid->column('patent_name', __('专利名称'));
        $grid->column('patent_type_id', __('专利类型'))->using(patent_type_select_option())->width(80);
        $grid->column('patent_sn', __('patent_sn'));
        $grid->column('apply_date', __('申请日'))->sortable()->width(100);
        $grid->column('department.name', __('dept_name'));
        $grid->column('agency.name', __('代理机构'))->modal('详情', PatentAgencyDetailRenderAble::class);
        $grid->column('legal_status', __('法律状态'))->using(['已受理', '等待实审提案']);
        $grid->disableCreateButton();
        $grid->actions(function (Actions $actions) {
            $actions->disableView();
            $row = $actions->row;
            if ($row->legal_status == 1) {
                $actions->append('&nbsp;&nbsp;<a>加速授权</a>');
            }

        });
        return $content
            ->title('已受理')
            ->body($grid);
    }

    public function edit(Content $content, $id)
    {
        return $content->title('已授权专利')
            ->body($this->form()->edit($id));
    }

    public function update($id)
    {
        return $this->form()->update($id);
    }

    protected function form()
    {
        $form = $this->repository->form();
        $form->text('patent_name', __('Patent name'))->required();
        $form->text('patent_sn', __('Patent sn'))->rules('required|regex:/^[a-zA-Z0-9X\.]+$/', [
            'regex'    => __('Patent sn') . '组成：只能为字母、数字、点',
            'required' => __('Patent sn') . '不能为空',
        ]);
        $form->date('apply_date', __('Apply date'))->required();
        $form->date('publication_date', __('公告日'));
        $form->text('publication_num', __('公告号'));
        $form->text('applicant', __('Applicant'));
        $form->text('charge_person', __('专利负责人'))->required()->help('第一发明人');
        $form->radio('patent_type_id', '专利类型')->required()->options(patent_type_select_option())
            ->when(4, function (Form $form) {
                $form->text('other_patent_sn', '国内申请号')->width('200px');
            })->when(5, function (Form $form) {
                $form->text('country', '具体国家')->width('200px');
                $form->radio('apply_channel', '申请途径')->default(0)->options(PatentApply::APPLY_CHANNEL);
                $form->text('other_patent_sn', '申请号')->width('200px');
            });
        $form->text('inventor', __('inventor'));
        $form->select('department_id', __('dept_name'))->options(Department::departmentOptions());
        $form->saving(function (Form $form) {
            if ($form->isEditing()) {
                $model = $form->model();
                try {
                    $form->patent_sn = PatentService::check_patent_sn($form->patent_sn, $form->patent_type_id);
                } catch (MsgException $exception) {
                    return back()->withInput(request()->all())->withErrors(['patent_sn' => $exception->getMessage()]);
                }
                if ($form->patent_sn != $model['patent_sn']) {
                    $res = $this->repository->newQuery()->where('patent_sn', $form->patent_sn)->first();
                    if ($res) {
                        return back()->withInput()->withErrors(['patent_sn' => '已存在不能重复添加']);
                    }
                }
                if ($model instanceof PatentApply) {
                    $model->patent()->update([
                        'patent_name'      => $form->patent_name,
                        'patent_sn'        => $form->patent_sn,
                        'apply_date'       => $form->apply_date,
                        'publication_num'  => $form->apply_date,
                        'publication_date' => $form->publication_date,
                        'applicant'        => $form->applicant,
                        'inventor'         => $form->inventor,
                        'patent_type_id'   => $form->patent_type_id,
                        'user_id'          => $model['user_id'],
                        'department_id'    => $model['department_id'],
                        'patent_person'    => $model['patent_person'],
                        'legal_status'     => '已授权',
                    ]);
                }
            }
        });
        return $form;
    }

    public function destroy($id)
    {
        return $this->form()->destroy($id);
    }
}
